package com.example.module_detail.model

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.bawei.common.entity.MovieVideoEntity
import com.example.module_detail.api.DetailServerApi
import com.example.network.BaseResponse
import com.example.network.HttpInterceptorType
import com.example.network.HttpManager

import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/2/10
 * Desc: Paging的数据源对象
 */
class MovieDetailPagingSource constructor(private val typeId: Int = -1, private val pageSize: Int = 10): PagingSource<Int, MovieVideoEntity>(){

//    @Inject lateinit var apiServer: MovieServerApi

    /**
     * 获取刷新页面的唯一标识Key
     */
    override fun getRefreshKey(state: PagingState<Int, MovieVideoEntity>): Int? {
        return state.anchorPosition?.let { anchorPosition ->
            val anchorPage = state.closestPageToPosition(anchorPosition)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    /**
     * 加载数据
     */
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MovieVideoEntity> {
        try {
            var currentPage = params.key ?: 1 //默认为第一页数据
            val loadSize = params.loadSize //加载多少条数据

            //创界API接口对象，并请求网络接口数据
            val apiServer = HttpManager.createApiServer<DetailServerApi>(DetailServerApi::class.java, HttpInterceptorType.INTERCEPTOR)
            var response: BaseResponse<List<MovieVideoEntity>> = if (typeId == -1){
                apiServer.getRecommendMultiVideo(currentPage, pageSize)
            } else {
                apiServer.getMultiVideoByTypeId(typeId, currentPage, pageSize)
            }

            //使用对象解构获取返回字段
            val (code, data, msg) = response

            //计算上一页KEY
            val prePageKey: Int ? = (currentPage - 1).run { if (this == 0) null else this}
            //计算下一页KEY
            val nextPageKey: Int? = when{
                loadSize > pageSize -> loadSize/ pageSize + 1
                code == 0 -> currentPage + 1
                else -> null
            }

            //返回数据对象
            return LoadResult.Page(data, prePageKey, nextPageKey)
        } catch (e: Exception){
            e.printStackTrace()
            return LoadResult.Error(e)
        }

    }


}